using Microsoft.AspNetCore.Mvc;
using PandaWebAPI.Models;
using PandaWebAPI.Models.ef;
using PandaWebAPI.Services;

namespace PandaWebAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpGet]
        public async Task<ActionResult<ApiResponse<List<User>>>> GetUsers()
        {
            try
            {
                var users = await _userService.GetAllAsync();
                return Ok(ApiResponse<List<User>>.Ok(users, "获取用户列表成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<List<User>>.Error($"获取用户列表失败: {ex.Message}"));
            }
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResponse<User>>> GetUserById(Guid id)
        {
            try
            {
                var user = await _userService.GetByIdAsync(id);
                if (user == null)
                    return NotFound(ApiResponse<User>.Error("用户不存在"));

                return Ok(ApiResponse<User>.Ok(user, "获取用户成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<User>.Error($"获取用户失败: {ex.Message}"));
            }
        }

        [HttpPost]
        public async Task<ActionResult<ApiResponse<User>>> CreateUser(User user)
        {
            try
            {
                var createdUser = await _userService.CreateAsync(user);
                return Ok(ApiResponse<User>.Ok(createdUser, "创建用户成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<User>.Error($"创建用户失败: {ex.Message}"));
            }
        }

        [HttpPut]
        public async Task<ActionResult<ApiResponse<User>>> UpdateUser(User user)
        {
            try
            {
                var updatedUser = await _userService.UpdateAsync(user);
                return Ok(ApiResponse<User>.Ok(updatedUser, "更新用户成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<User>.Error($"更新用户失败: {ex.Message}"));
            }
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResponse<bool>>> DeleteUser(Guid id)
        {
            try
            {
                var result = await _userService.DeleteAsync(id);
                if (!result)
                    return NotFound(ApiResponse<bool>.Error("用户不存在"));

                return Ok(ApiResponse<bool>.Ok(true, "删除用户成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiResponse<bool>.Error($"删除用户失败: {ex.Message}"));
            }
        }
    }
}